<?php

namespace common\jobs;

use common\models\mongo\DynamicMessCount;
use console\models\UserForDynamicLogic;
use Yii;
use common\models\user\User;
use common\models\mongo\DynamicMess;
use console\models\logics\DynamicCommentMessLogic;
use console\models\logics\DynamicMessLogic;
use yii\base\Exception;

/**
 * 动态哦消息提醒队列任务
 * Class DynamicAtNotice
 */
class DynamicMessageJob extends \yii\base\BaseObject implements \yii\queue\JobInterface {

    /**
     * 多用户,此时适用于被动用户为空
     */
    public $usernames;
    /**
     * @var array $active_input 主动行为者用户数集
     * [
     *   'user_id',
     *   'dynamic_id',
     *   'comment_id',
     * ]
     */
    public $active_input;

    /**
     * @var array $passive_input 被动行为者用户数集,被动用户集可以有多个,遍历集成数据,多用户集一般只适用于@多用户时
     * [
     *   [
     *      'user_id',
     *      'dynamic_id',
     *      'comment_id',
     *  ],...
     * ]
     */
    public $passive_input;

    /**
     * @var $mess_type
     * replay:  active_data(回复内容主体,comment_id && dynamic_id ),   passive_data(单一 && comment_id && dynamic_id  )
     * comment:  active_data(评论内容主体,comment_id && dynamic_id),  passive_data(单一 && comment_id==null   )
     * @:  active_data(comment_id  ||  dynamic_id ),  passive_data(为空)
     * 赞:  active_data(为空),  passive_data( comment_id || dynamic_id )
     */
    public $mess_type;

    private $active_data;
    private $passive_data;

    /**
     *
     * 精细格式数据
     ***************************************************
     *
     *  passive_user_id   被动赞 @ 评 等...用户的id
     *  active_user_id  主动赞 @ 评 等....的用户id
     *  active_data=>{
     *      "user_info",
     *      "dynamic",
     *      "comment",
     * },
     *  passive_data=>{
     *      "user_info",
     *      "dynamic",
     *      "comment",
     * },
     * created_at
     * updated_at
     * deleted_at
     ***************************************************
     * 简化格式数据
     *
     * mess_type
     * passive_user_id
     * dynamic
     * content
     * user_info
     * created_at
     * updated_at
     */
    public function execute($queue) {
        Yii::error("[DynamicMessaegJob BEGIN] \r\n ------------------- BEGIN ----------------", 'queue');
        try {
            //快捷过滤名称用户组
            $this->usernamesToUserIds();

            $dynamicMess = new DynamicMess();
            $dynamicMess->mess_type = $this->mess_type;
            $this->activeData($dynamicMess, $this->active_input);
            if ($this->passive_input) {
                foreach ($this->passive_input as $passive) {
                    $_dynamicMess = clone $dynamicMess;
                    //加载用户数据集
                    $this->passiveData($_dynamicMess, $passive);
                    $this->extractContent($_dynamicMess);

                    if ($_dynamicMess->save()) {
                        //累计新消息数量
                        $dynamicMessCount = DynamicMessCount::findOne(['user_id' => $_dynamicMess->passive_user_id]);
                        if (!$dynamicMessCount) {
                            $dynamicMessCount = new DynamicMessCount();
                            $dynamicMessCount->user_id = $_dynamicMess->passive_user_id;
                        }
                        $dynamicMessCount->mess_cnt += 1;
                        $dynamicMessCount->save();
                    }
                }
            }
        } catch (\Exception $e) {
            $errMsg = [
                'usernames' => $this->usernames,
                'passive_input' => $this->active_input,
                'active_input' => $this->active_input,
                'active_data' => $this->active_data,
                'passive_data' => $this->passive_data,
                'mess_type' => $this->mess_type,
                'err_msg' => $e->getFile() . ' ' . $e->getMessage() . ' ' . $e->getLine(),
            ];
            Yii::error('[DynamicMessaegJob EXECUTE]' . print_r($errMsg, true), 'queue');
        }

        Yii::error("[DynamicMessaegJob END] \r\n ------------------- END ----------------", 'queue');
    }

    /**
     * 提取 转发/评论/回复 等信息内容
     * @param $dynamicMess
     * @return mixed
     */
    private function extractContent(&$dynamicMess) {
        $dynamicMess->user_info = $this->active_data['user_info'];

        $activeDataDynamic = $this->active_data['dynamic'];
        $activeDataComment = $this->active_data['comment'];

        $dynamicMess->dynamic = $this->passive_data['dynamic'];

        switch ($this->mess_type) {
            case DynamicMess::MESS_TYPE_REPLY:
                $dynamicMess->content = $activeDataComment['post'];
                break;
            case DynamicMess::MESS_TYPE_COMMENT:
                $dynamicMess->content = $activeDataComment['post'];
                break;
            case DynamicMess::MESS_TYPE_SEND:
                $dynamicMess->content = $activeDataDynamic['text'];
                break;
            case DynamicMess::MESS_TYPE_AT:
                $dynamicMess->dynamic = $activeDataDynamic;
                break;
            case DynamicMess::MESS_TYPE_LIKE:
                $dynamicMess->dynamic = $activeDataDynamic;
                break;
            default:
                $dynamicMess->content = null;
                $this->_err('消息类型是不被允许的类型');
        }
        return $dynamicMess;
    }

    private function usernamesToUserIds() {
        if ($this->usernames && empty($this->passive_input)) {
            $users = User::findAll(['username' => $this->usernames]);
            foreach ($users as $u) {
                $user['user_id'] = $u->id;
                $this->passive_input[] = $user;
            }
        }
        return $this->passive_input;
    }

    private function passiveData(&$dynamicMess, $passive) {
        $passiveUser = $this->user($passive['user_id']);

        $dynamicMess->passive_user_id = $passiveUser['id'];
        $passiveData = [];
        $passiveData['user_info'] = $passiveUser;
        $passiveData['dynamic'] = $this->dynamic($passive);
        $passiveData['comment'] = $this->comment($passive);
        $this->passive_data = $passiveData;

//        $dynamicMess->passive_data = $passiveData;
//        $dynamicMess->dynamic = $this->passive_data['dynamic'];

        return $dynamicMess;
    }

    private function activeData(&$dynamicMess, $active) {
        $activeUser = $this->user($active['user_id']);
//        $dynamicMess->active_user_id = $activeUser['id'];

        $activeData = [];
        $activeData['user_info'] = $activeUser;
        $activeData['dynamic'] = $this->dynamic($active);
        $activeData['comment'] = $this->comment($active);
//        $dynamicMess->active_data = $activeData;
        $this->active_data = $activeData;

        return $dynamicMess;
    }

    private function dynamic($data) {
        if (!isset($data['dynamic_id'])) {
            return null;
        }

        $dynamic = DynamicMessLogic::find()
            ->where(['id' => $data['dynamic_id']])
            ->one();

        return $dynamic ? $dynamic->toArray() : null;
    }

    private function comment($data) {
        if (!isset($data['comment_id']) || !isset($data['dynamic_id'])) {
            return null;
        }

        $comment = DynamicCommentMessLogic::findx($data['dynamic_id'])
            ->where(['id' => $data['comment_id']])
            ->one();
        return $comment ? $comment->toArray() : null;
    }

    private function user($id) {
        try{
            $user = UserForDynamicLogic::findOne($id);
        } catch (\Exception $exception){
            $this->_err($exception->getFile() . ' ' . $exception->getMessage() . ' ' . $exception->getLine());
            throw new $exception;
        }
        return $user->toArray();
    }

    private function _err($e) {
        Yii::error("[DynamicMessaegJob TRACE]\r\n------------------------TRACE BEGIN--------------------------\r\n" .
            print_r($e, true) .
            "\r\n------------TRACE END--------------", 'queue');
    }
}
